package networkSimulation.monitor

import collection.mutable.Subscriber
import networkSimulation.framework.Graph
import java.util.Calendar
import java.text.SimpleDateFormat
import java.io.{IOException, BufferedWriter, FileWriter}

/**
 * Abstract Monitor
 *
 * @author  Tim Caljé
 *          Jeroen De Raedt
 *          Jorick Van Aken
 */
abstract class Monitor[Evt, Pub, N, E](val name : String,val graph : Graph[N, E], var logEnabled : Boolean) extends Subscriber[Evt, Pub] {

  // Additional constructor
  def this(name : String,graph : Graph[N, E]) = this(name, graph, true)

  /**
   * Interface which is called by the observed object
   */
  def notify(pub: Pub,  event: Evt)

  /**
   * Create a log message from a given message string
   * @param msg: String
   *        The message which will be logged
   */
  protected def log(msg: String) {
   // get current time
    val today = Calendar.getInstance().getTime()
    val log = name + " LOG " + new SimpleDateFormat("hh").format(today) + ":" + new SimpleDateFormat("mm").format(today) + " " + new SimpleDateFormat("a").format(today) + ": " + msg;
    if (logEnabled) {
      // print log
      println(log)
    }
    // write log to file
    writeLog(log)
  }

  private def writeLog(msg: String) {
    try{
    // Create file
    var fstream : FileWriter = new FileWriter("out.txt",true);
    var out : BufferedWriter = new BufferedWriter(fstream);
    out.write(msg + "\n");
    //Close the output stream
    out.close();
    }catch {
      case e: Exception => throw e
    }
  }

}